package com.mrd.projects.weixinapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mrd.projects.weixinapi.dbutil.HongBaoTaskDao;
import com.mrd.projects.weixinapi.entity.HongBaoTask;
import com.mrd.projects.weixinapi.entity.StateEnum;
import com.mrd.projects.weixinapi.util.BizUtil;
import com.mrd.projects.weixinapi.util.WeixinApiConfigUtil;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Hello world!
 */
public class App {
	private static Map<String, String>	COOKIE_MAP	= null;

	public static void main(String[] args) {
		try {
			App app = new App();
			for(int i = 0;i < 1;i++) {
				app.sendHongBao(new HongBaoTask()
				        .setTemplate_id(WeixinApiConfigUtil.getValue("hongbao.login"))
				        .setUser_account("xiaoli1024").setBizids("BE" + System.currentTimeMillis())
				        .setAmount(1).setBillno(BizUtil.generateBillNo()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean isReturnTure(Object result){
		if(result instanceof  Exception){
			return false;
		}
		try{
			return Boolean.valueOf(result.toString());
		}catch (Exception e){}
		return true;
	}

	private Object login() {
		try {
			Connection conn = Jsoup.connect(WeixinApiConfigUtil.getServerBaseUrl() + "/"
			        + Math.random()).method(Connection.Method.GET);
			if(null != COOKIE_MAP) {
				conn.cookies(COOKIE_MAP);
			}
			Connection.Response resp1 = conn.execute();
			COOKIE_MAP = resp1.cookies();
			Document doc = Jsoup
			        .connect(WeixinApiConfigUtil.getServerBaseUrl() + "/" + Math.random())
			        .cookies(COOKIE_MAP).get();
			COOKIE_MAP.put(WeixinApiConfigUtil.getServerCsrfName(), doc
			        .getElementsByAttributeValue("name", WeixinApiConfigUtil.getServerCsrfName())
			        .val());
			Connection.Response resp2 = Jsoup
			        // .connect(WeixinApiConfigUtil.getServerBaseUrl() + "/fromerp/")
			        .connect(WeixinApiConfigUtil.getServerBaseUrl() + "/hongbao.request.do")
			        .data("appid", WeixinApiConfigUtil.getAccount().getAppid())
			        .data("appsecret", WeixinApiConfigUtil.getAccount().getAppsecret())
			        .cookies(COOKIE_MAP)
			        .data(WeixinApiConfigUtil.getServerCsrfName(), COOKIE_MAP.get(WeixinApiConfigUtil
			                .getServerCsrfName())).method(Connection.Method.POST).execute();
		} catch (java.net.ConnectException ex) {
			return ex;
		} catch (IOException e) {
			return e;
		} catch (IllegalArgumentException e) {
			System.out.println("请检查weixinapi.properties参数配置是否错误。");
			return e;
		}
		return true;
	}

	public void sendHongBao(HongBaoTask task) throws Exception {
		if(null != task && null == task.getBillno()) {
			task.setBillno(BizUtil.generateBillNo());
		}
		sendHongBao(task, true);
	}

	private void sendHongBao(HongBaoTask task,boolean allowRetry) throws Exception {
		HongBaoTaskDao dao = new HongBaoTaskDao();

		if(null == task || StringUtil.isBlank(task.getBillno())
		        || StringUtil.isBlank(task.getTemplate_id())
		        || StringUtil.isBlank(task.getUser_account())) {
			Exception ee = new Exception("红包任务参数异常。");
			if(null != task) {
				task.setState(StateEnum.FAIL);
				task.setRemark(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
				        + ee.getMessage());
				if(task.getId() == 0) {
					dao.save(task);
				} else {
					dao.update(task);
				}
			}
			throw ee;
		}
		if(WeixinApiConfigUtil.getAccount() == null) {
			throw new Exception("微信API配置异常。");
		}

		if(null == COOKIE_MAP) {
			Object loginResult = login();
			if(App.isReturnTure(loginResult)) {
				sendHongBao(task, allowRetry);
				return;
			} else {
				if(task.getId() == 0) {
					dao.save(task);
				}
				System.out.println(WeixinApiConfigUtil.getAccount().getAppid() + "登录微信红包接口系统失败。");
				if(loginResult instanceof  Exception) {
					throw (Exception) loginResult;
				}
			}
		}

		try {
			Connection conn = Jsoup
			        // .connect(WeixinApiConfigUtil.getServerBaseUrl() + "/fromerp/sendHongBao")
			        .connect(WeixinApiConfigUtil.getServerBaseUrl() + "/hongbao.request.do")
			        .cookies(COOKIE_MAP)
			        .data(WeixinApiConfigUtil.getServerCsrfName(), COOKIE_MAP.get(WeixinApiConfigUtil
			                .getServerCsrfName())).data("template_id", task.getTemplate_id())
			        .data("user_account", task.getUser_account())
			        .data("amount", task.getAmount() + "").data("erp_billno", task.getBillno())
			        .data("bill_detail", task.getBizids()).method(Connection.Method.POST)
			        .ignoreContentType(true);
			Connection.Response resp = conn.execute();
			COOKIE_MAP = null;

			if(resp.body().contains("<html") && resp.body().contains("initOauth")) {

				if(allowRetry) {
					Object loginResult = login();
					if(App.isReturnTure(loginResult)){
						sendHongBao(task, false);
					}
					else{
						if(loginResult instanceof  Exception) {
							throw (Exception) loginResult;
						}
					}
				} else {
					task.setState(StateEnum.FAIL);
					task.setRemark(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
					        + "重试登录失败");
					if(task.getId() == 0) {
						dao.save(task);
					} else {
						dao.update(task);
					}
				}
				return;
			}
			JSONObject jresult = JSON.parseObject(resp.body());
			if("SHB400".equals(jresult.getString("errcode"))
			        || "SHB502".equals(jresult.getString("errcode"))) {
				if(task.getId() != 0) {
					task.setRemark(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					task.setState(StateEnum.SUCCESS);
					dao.update(task);
				} else {
					task.setRemark(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					task.setState(StateEnum.SUCCESS);
					dao.save(task);
				}
			} else {
				task.setState(StateEnum.FAIL);
				task.setRemark(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
				        + jresult.getString("errmsg"));
				if(task.getId() == 0) {
					dao.save(task);
				} else {
					dao.update(task);
				}
			}

			HongBaoTask ntask = dao.findNextTask();
			if(null != ntask) {
				sendHongBao(ntask, false);
			}
		} catch (org.jsoup.HttpStatusException e1) {
			System.out.println("服务端异常:" + e1.getStatusCode());
			if(allowRetry) {
				Object loginResult = login();
				if(App.isReturnTure(loginResult)){
					sendHongBao(task, false);
				}
				else{
					if(loginResult instanceof  Exception) {
						throw (Exception) loginResult;
					}
				}
			} else {
				if(task.getId() == 0) {
					dao.save(task);
				}
				throw  e1;
			}
		} catch (java.net.ConnectException ex) {
			if(task.getId() == 0) {
				dao.save(task);
			}
			System.out.println("服务器连接不上");
			throw  ex;
		} catch (IOException e) {
			if(task.getId() == 0) {
				dao.save(task);
			}
			System.out.println("服务器连接异常");
			throw  e;
		} catch (Exception e) {
			System.err.println(e.getMessage());
			throw  e;
		}
	}
}
